from django.shortcuts import render,HttpResponse
from . import models
import json
import random
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr


my_sender = 'SEhyyy2020@163.com'  # 发件人邮箱账号
my_pass = 'PMOTDIXEPODXYDRK'  # 发件人邮箱密码
# Create your views here.

def GenerateAuthCode():
    #生成随机验证码
    auth_code=''
    for i in range(4):   # 循环4次
        index=random.randrange(0,3)   # 生成0-3中的一个数
        if index==0:
            auth_code+=chr(random.randint(97,122))  # 生成a-z中的一个小写字母
        elif index==1:
            auth_code+=chr(random.randint(65,90))    # 生成A-Z中的大写字母
        else:
            auth_code+=str(random.randint(1,9))    # 生成1-9的一个数字
    return(auth_code)



def SendAuthCode(user_email,auth_code,uid):

    url = 'http://47.94.130.28:8000/user/verify?'+'ucode=' + uid + auth_code
    #向邮箱发送验证连接
    msg = MIMEText('''
            <p>欢迎使用清华帮！</p>
            <a href=" ''' + url + ''' ">请点击此处进行验证</a>
            <p>或手动将以下网址输入浏览器中</p>
            <p>''' + url + '''</p>
        '''
        ,'html','utf-8')
    msg['From'] = formataddr(["火炏焱燚", my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
    msg['To'] = formataddr(["注册用户", user_email])  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
    msg['Subject'] = "清华帮注册验证码"  # 邮件的主题，也可以说是标题

    server = smtplib.SMTP_SSL("smtp.163.com", 465)  # 发件人邮箱中的SMTP服务器，端口是25
    server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
    server.sendmail(my_sender, [user_email, ], msg.as_string())  #括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
    server.quit()  # 关闭连接




def RegisterView(request):
    valid = False
    try:
        if(request.method == 'POST'):
            #获取前端返回数据
            json_result = json.loads(request.body.decode())
            user_name = json_result.get('user_name')
            nick_name = json_result.get('nick_name')
            user_code = json_result.get('user_code')
            user_email = json_result.get('user_email')
            
            #为用户分配唯一ID
            uid = "U" + str(models.User.objects.count()).zfill(15)
        
            #邮箱唯一性核查
            if(models.User.objects.filter(UserEmail=user_email).exists()):
                message = "注册失败，邮箱已存在"
                
            #用户名唯一性核查
            elif(models.User.objects.filter(UserName=user_name).exists()):
                message = "注册失败，用户名已存在"
            
            #用户名长度核查
            elif(len(user_name)<3 or len(user_name)>20):
                message = "用户名长度应位于3-20字符之间"
                
            #昵称长度核查
            elif(len(nick_name)<3 or len(nick_name)>20):
                message = "昵称长度应位于3-20字符之间"
                
            #密码长度核查
            elif(len(user_code)<6 or len(user_code)>16):
                message = "密码长度应位于6-16字符之间"
                
                
            #添加数据
            else:
                real_user_email = json_result.get('user_email') + "@mails.tsinghua.edu.cn"
                auth_code = GenerateAuthCode()
                SendAuthCode(real_user_email,auth_code,uid)
                user = models.User(UID = uid, UserName=user_name,NickName = nick_name, UserCode=user_code, UserEmail=user_email, UserPhone="", UserVXID = "", UserAuthCode = auth_code, UserStatus = False) 
                user.save()
                valid = True
                message = "注册成功"
            
    except:
        message = "未知错误"
    
    result = {
        'valid':valid,
        'message':message,
    }
    return HttpResponse(json.dumps(result,ensure_ascii=False),content_type="application/json,charset=utf-8")




def LoginView(request):
    
    try:
        if(request.method == 'POST'):
            #获取前端返回数据
            json_result = json.loads(request.body.decode())
            user_code = json_result.get('user_code')
            user_name = json_result.get('user_name')
            
            #寻找是否存在对应的邮箱与密码
            if(models.User.objects.filter(UserCode=user_code,UserName=user_name).exists()):
                #数据库查询
                user = models.User.objects.get(UserName = user_name)
                uid = user.UID
                nick_name = user.NickName
                user_email = user.UserEmail
                user_phone = user.UserPhone
                user_vxid = user.UserVXID
                user_status =  user.UserStatus
                image_src = ""
                
                #向前端发送数据
                result = {
                    'valid': True,
                    'uid': uid,
                    'user_name': user_name,
                    'nick_name': nick_name,
                    'user_email': user_email,
                    'user_phone': user_phone,
                    'user_vxid': user_vxid,
                    'image_src': image_src,
                    'user_status': user_status,

                }
                
                
            else:
                result = {
                    'valid': False,
                }
    except:
        result = {
            'valid': False,
        }
    return HttpResponse(json.dumps(result,ensure_ascii=False),content_type="application/json,charset=utf-8")




def UserInfoSetView(request):
    valid = False
    try:
        if(request.method == 'POST'):
            #获取前端返回数据
            json_result = json.loads(request.body.decode())
            uid = json_result.get('uid')
            user_name = json_result.get('user_name')
            nick_name = json_result.get('nick_name')
            user_email = json_result.get('user_email')
            user_phone = json_result.get('user_phone')
            user_vxid = json_result.get('user_vxid')
            
            #邮箱唯一性核查
            if(models.User.objects.filter(UID = uid, UserEmail = user_email).exists()==False and models.User.objects.filter(UserEmail=user_email).exists()):
                message = "邮箱已被其他用户占用"
                
            #用户名唯一性核查
            elif(models.User.objects.filter(UID = uid, UserName = user_name).exists()==False and models.User.objects.filter(UserName=user_name).exists()):
                message = "用户名已被其他用户占用"
            
            #用户名长度核查
            elif(len(user_name)<3 or len(user_name)>20):
                message = "用户名长度应位于3-20字符之间"
                
            #昵称长度核查
            elif(len(nick_name)<3 or len(nick_name)>20):
                message = "昵称长度应位于3-20字符之间"
                
            #手机号码长度和格式
            elif(len(user_phone) != 0 and (len(user_phone)!=11 or user_phone.isdigit()==False)):
                message = "手机号码应为11位数字"
                
            #添加数据
            else:
                #执行更改
                user = models.User.objects.get(UID = uid)
                
                #若邮箱变化，则重新发送验证邮件
                if (user.UserEmail != user_email):
                    real_user_email = user_email + "@mails.tsinghua.edu.cn"
                    auth_code = GenerateAuthCode()
                    SendAuthCode(real_user_email,auth_code)
                    user.UserAuthCode = auth_code
                    user.UserStatus = False
                    
                user.UserName = user_name
                user.NickName = nick_name
                user.UserEmail = user_email
                user.UserPhone = user_phone
                user.UserVXID = user_vxid
                user.save()
                valid = True
                message = "修改成功"
            
    except:
        message = "未知错误"
    
    result = {
        'valid':valid,
        'message':message,
    }
    
    return HttpResponse(json.dumps(result,ensure_ascii=False),content_type="application/json,charset=utf-8")



def PasswordChangeView(request):
    valid = False
    try:
        if(request.method == 'POST'): 
            #获取前端返回数据
            json_result = json.loads(request.body.decode())
            uid = json_result.get('uid')
            old_code = json_result.get('old_code')
            new_code = json_result.get('new_code')
            
            #验证旧密码的正确性
            if(models.User.objects.filter(UID = uid, UserCode = old_code).exists()==False):
                message = "原密码错误"
                
            #验证新密码是否符合规范
            elif(len(new_code)<6 or len(new_code)>16):
                message = "新密码长度应位于6-16字符之间"
            
            #更改密码
            else:
                user = models.User.objects.get(UID = uid)
                user.UserCode = new_code
                user.save()
                valid = True
                message = "修改成功"
                
    except:
        message = "未知错误"
    
    result = {
        'valid':valid,
        'message':message,
    }
    
    return HttpResponse(json.dumps(result,ensure_ascii=False),content_type="application/json,charset=utf-8")
                
                
def VerifyView(request):
    message = "验证失败，请检查注册信息"
    try:
        #获取前端返回数据
        uid = (request.GET['ucode'])[0:16]
        auth_code = (request.GET['ucode'])[16:]
        
        if(models.User.objects.filter(UID = uid, UserAuthCode = auth_code).exists()):
            user = models.User.objects.get(UID = uid)
            user.UserStatus = True
            user.save()
            message = "验证成功，欢迎使用清华帮！"
                
    except:
        message = "验证失败，请检查注册信息"
        
    return HttpResponse(message)    
